package com.app.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatTextView

class RecStateTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private val paint = Paint().apply {
        color = Color.RED
        isAntiAlias = true
    }

    private val size = 8f.dp
    init {
        setPadding(paddingLeft + (size * 4).toInt(),paddingTop,paddingRight,paddingBottom)
    }
//    override fun onDraw(canvas: Canvas) {
//        super.onDraw(canvas)
//        val c = height / 2f
//        canvas.drawCircle(c + paddingLeft,c,size,paint)
//    }

    private var cx = 0f
    private val DURATION = 800L
    private val workTask = object :Runnable{
        override fun run() {
            display = !display
            invalidate()
            postDelayed(this,DURATION)
        }
    }
    private var display = false
    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)

        cx = (right - left) /2f
        invalidate()
    }
    private fun drawPoint(canvas: Canvas){
        if (display) {
            canvas.drawCircle(cx,cx,cx,paint)
        }
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.also {
            drawPoint(it)
        }
    }

    private fun start(){
        postDelayed(workTask,0)
    }
    private fun stop(){
        display = false
        removeCallbacks(workTask)
    }
    override fun onVisibilityChanged(changedView: View, visibility: Int) {
        super.onVisibilityChanged(changedView, visibility)

        if (visibility == View.VISIBLE) {
            start()
        }else{
            stop()
        }
    }
}